package cn.sczc.jh.client.controller.login;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.sczc.jh.client.base.AbstractController;
import cn.sczc.jh.client.entity.User;
import cn.sczc.jh.client.exception.BusinessException;

@Controller
public class LoginController extends AbstractController {

//	@Autowired
//	private UserService userService;
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public ResponseEntity<ModelMap> doLogin(ModelMap modelMap, HttpSession session,
			@RequestBody Map<String, Object> params) {
		String username = (String) params.get("username");
		String password = (String) params.get("password");
		// 添加用户认证信息
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		try {
			subject.login(usernamePasswordToken);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			throw new BusinessException("账号或密码错误！");
		} catch (AuthorizationException e) {
			e.printStackTrace();
			throw new BusinessException("没有权限");
		}
		if (subject.isAuthenticated()) {
			User user = (User) subject.getPrincipal();
			return setSuccessModelMap(modelMap, user);
		}
		throw new BusinessException("账号或密码错误！");
	}

	@RequestMapping(value = "logout")
	public ResponseEntity<ModelMap> logout(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return setSuccessModelMap(modelMap);
	}
}
